<template>
  <div class="searchTea">
    <div>
      <el-input
        style="margin-right: 30px"
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        v-model="teaName"
      >
      </el-input>
      <el-button @click="getSearchResult" type="success" icon="el-icon-search"
        >搜索</el-button
      >
    </div>
  </div>
</template>

<script>
import { getRequest } from "../../util/request";
export default {
  name: "searchTea",
  data() {
    return {
      teaName: "",
    };
  },
  methods: {
    //点击搜索按钮，请求数据
    getSearchResult() {
      if (this.teaName.trim() !== "") {
        let requestResult = getRequest(
          "user/selSearchProduct",
          `?value=${this.teaName}`
        );
        requestResult.then(
          (response) => {
            if (response.data.length) {
              this.$bus.$emit("searchResult", response.data);
              // console.log("response.data", response.data);
            } else {
              this.$message({
                showClose: true,
                message: "未找到搜索的商品哟！",
                type: "warning",
              });
            }
          },
          (err) => {
            throw err;
          }
        );
      } else {
        this.$bus.$emit("searchResult", false);
      }
    },
    //使用防抖，文本框输入内容，获取数据
    getInputResult() {
      let timer = null;
      return () => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          this.getSearchResult();
        }, 1000);
      };
    },
  },
  mounted() {
    const inputNode = document.querySelector("input");
    inputNode.addEventListener("input", this.getInputResult());
  },
  /* updated() {
    const inputNode = document.querySelector("input");
    inputNode.addEventListener("input", this.getInputResult());
  }, */
  beforeDestroy() {
    removeEventListener("input", this.getInputResult());
  },
};
</script>

<style scoped lang='less'>
.searchTea {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  & > div {
    width: 400px;
    height: 40px;
    display: flex;
  }
}
</style>